package ivan.bookKeeper;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import so.book.ReturnAllBooks;
import so.bookFromLibrary.ReturnAllBooksFromLibrary;
import so.library.ReturnAllLibraries;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import domain.Book;
import domain.BookFromLibrary;
import domain.Library;

public class ListBookFromLibraryActivity extends ListActivity {
	private static final String TAG = ListBookFromLibraryActivity.class
			.getSimpleName();
	private static ArrayList<BookFromLibrary> bookFromLibraryList;
	private static Map<Integer, Book> booksMap;
	private static Map<Integer, Library> libraryMap;
	private BaseAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_all_books_from_library);
		getAllBooks(ListBookFromLibraryActivity.this);
		getLibraries();
		getBooksFromLibraries();
		adapter = new BookFromLibraryAdapter(this);
		setListAdapter(adapter);
	}

	// // get all books & populate the array
	private void getAllBooks(Context context) {
		booksMap = new HashMap<Integer, Book>();
		Book book = new Book();
		AsyncTask<Object, Object, Object> getAllBooksTask = new ReturnAllBooks(
				this).execute(book);
		try {
			Cursor cursor = (Cursor) getAllBooksTask.get();
			while (cursor.moveToNext()) {
				int bookID = cursor.getInt(cursor
						.getColumnIndexOrThrow("bookID"));
				String bookName = cursor.getString(cursor
						.getColumnIndexOrThrow("bookName"));
				String bookAuthor = cursor.getString(cursor
						.getColumnIndexOrThrow("bookAuthor"));
				int bookYear = cursor.getInt(cursor
						.getColumnIndexOrThrow("bookYear"));
				String bookPublisher = cursor.getString(cursor
						.getColumnIndexOrThrow("bookPublisher"));
				String bookLanguage = cursor.getString(cursor
						.getColumnIndexOrThrow("bookLanguage"));
				String bookISBN = cursor.getString(cursor
						.getColumnIndexOrThrow("bookISBN"));

				book = new Book(bookYear, bookName, bookAuthor, bookPublisher,
						bookLanguage, bookISBN);
				book.setBookID(bookID);
				booksMap.put(book.getBookID(), book);
				Log.d(TAG, book.getBookID() + " " + book.toString());

			}

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// // helper function for getting ALL the libraries from db!
	private void getLibraries() {
		libraryMap = new HashMap<Integer, Library>();

		Library library = new Library();
		AsyncTask<Object, Object, Object> returnAllLibraries = new ReturnAllLibraries(
				this).execute(library);

		Cursor cursor = null;
		try {
			cursor = (Cursor) returnAllLibraries.get();
			if (cursor == null)
				showLongToast(getString(R.string.toastMessage_error_noLibrariesInDB));
			else {
				while (cursor.moveToNext()) {
					library = new Library(cursor.getInt(0), cursor.getInt(1),
							cursor.getInt(2), cursor.getString(3),
							cursor.getString(4), cursor.getString(5),
							cursor.getString(6));
					libraryMap.put(library.getLibraryID(), library);
					Log.d(TAG, "new library: " + library.toString());
				}
				Log.d(TAG,
						"Finished fetching libraries: adapter completed with data");
			}

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getBooksFromLibraries() {
		bookFromLibraryList = new ArrayList<BookFromLibrary>();
		BookFromLibrary bfl = new BookFromLibrary();
		AsyncTask<Object, Object, Object> getBFL = new ReturnAllBooksFromLibrary(
				this).execute(bfl);
		Log.d(TAG, "GOT CURSOR FOR BOOKSFROMLIBRARY!!");
		try {
			Cursor cursor = (Cursor) getBFL.get();

			while (cursor.moveToNext()) {
				int bookID = cursor.getInt(cursor
						.getColumnIndexOrThrow("bookID"));
				int libraryID = cursor.getInt(cursor
						.getColumnIndexOrThrow("libraryID"));
				int numExtend = cursor.getInt(cursor
						.getColumnIndexOrThrow("numExtend"));
				long date = cursor.getLong(cursor.getColumnIndexOrThrow("date"));
				Log.d(TAG, "MILISECONDS: " + date);
				bfl = new BookFromLibrary(libraryID, bookID);
				bfl.setMilliseconds(date);
				bfl.setNumExtend(numExtend);
				bookFromLibraryList.add(bfl);
				Log.d(TAG, "ADDED BOOK: " + bfl.getBookID() + " FROM LIBRARY: "
						+ bfl.getLibraryID() + ", DATE: "
						+ bfl.getMilliseconds());
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static class BookFromLibraryAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private Context context;

		public BookFromLibraryAdapter(Context context) {
			inflater = LayoutInflater.from(context);
			this.context = context;
		}

		@Override
		public int getCount() {
			return bookFromLibraryList.size();
		}

		@Override
		public Object getItem(int position) {
			return bookFromLibraryList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.book_from_library_row,
						null);
				holder = new ViewHolder();

				holder.bookName_textView = (TextView) convertView
						.findViewById(R.id.bookName);
				holder.bookAuthor_textView = (TextView) convertView
						.findViewById(R.id.bookAuthor);
				holder.libraryName_textView = (TextView) convertView
						.findViewById(R.id.libraryName);
				holder.borrowDate_textView = (TextView) convertView
						.findViewById(R.id.borrowDate);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			int bookID = bookFromLibraryList.get(position).getBookID();
			Log.d(TAG, position + ". BookID:" + bookID);
			Book book = booksMap.get(bookID);
			int libraryID = bookFromLibraryList.get(position).getLibraryID();
			Log.d(TAG, position + ". LibraryID:" + libraryID);
			Library library = libraryMap.get(libraryID);

			holder.bookName_textView.setText(book.getBookName());
			holder.bookAuthor_textView.setText(book.getBookAuthor());
			holder.libraryName_textView.setText(library.getLibraryName());
			holder.borrowDate_textView.setText(new Date(bookFromLibraryList
					.get(position).getMilliseconds()).toLocaleString());

			return convertView;

		}

		static class ViewHolder {
			TextView bookName_textView;
			TextView bookAuthor_textView;
			TextView libraryName_textView;
			TextView borrowDate_textView;
		}
	}

	private void showLongToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}
}
